package com.yc.system.service.impl;

import com.yc.common.constant.Constants;
import com.yc.common.core.domain.entity.SysPermission;
import com.yc.common.core.domain.entity.SysUser;
import com.yc.system.mapper.SysPermissionMapper;
import com.yc.system.mapper.SysUserMapper;
import com.yc.system.service.ISysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 权限服务实现
 *
 * @Author YanChen
 * @Date 2025/4/13 13:50
 **/
@Service
public class SysPermissionServiceImpl implements ISysPermissionService {

    @Autowired
    private SysPermissionMapper permissionMapper;

    @Autowired
    private SysUserMapper userMapper;

    /**
     * 根据用户ID查询权限
     */
    @Override
    public ConcurrentHashMap<String, Set<String>> selectPermissionsByUserId(Long userId) {
        ConcurrentHashMap<String, Set<String>> permsMap = new ConcurrentHashMap<>();
        // 管理员拥有所有权限
        SysUser user = userMapper.selectById(userId);
        if (user != null && "0".equals(user.getUserType())) {
            Set<String> perms = new HashSet<>();
            perms.add(Constants.ALL_PERMISSION); // 所有权限
            permsMap.put("*", perms);
            return permsMap;
        }
        //其余用户查询拥有的权限列表
        Set<String> permissions = permissionMapper.selectPermissionsByUserId(userId);
        if (permissions != null && !permissions.isEmpty()) {
            for (String perm : permissions) {
                // 拆分出模块名，例如 user:add → user 是模块
                String[] parts = perm.split(":");
                if (parts.length > 0) {
                    String module = parts[0];
                    permsMap.computeIfAbsent(module, k -> new HashSet<>()).add(perm);
                }
            }
        }
        return permsMap;
    }

    /**
     * 根据菜单ID查询权限
     */
    @Override
    public List<SysPermission> selectPermissionsByMenuId(Long menuId) {
        return List.of();
    }

    /**
     * 获取用户所有权限
     */
    @Override
    public Set<String> getUserPermissions(Long userId) {
        return Set.of();
    }

}
